// 微信小程序OSS上传工具
class OSSUpload {
  constructor() {
    this.baseURL = 'https://baiyumei.oss-cn-hangzhou.aliyuncs.com';
  }

  /**
   * 获取OSS上传凭证
   */
  async getUploadCredentials() {
    try {
      // 从你的后端获取临时凭证
      const res = await uni.request({
        url: '/api/oss/credentials', // 你的后端接口
        method: 'POST'
      });
      return res.data;
    } catch (error) {
      console.error('获取OSS凭证失败:', error);
      throw error;
    }
  }

  /**
   * 上传文件到OSS
   */
  async uploadFile(filePath, options = {}) {
    try {
      // 1. 获取上传凭证
      const credentials = await this.getUploadCredentials();
      
      // 2. 构造上传参数
      const formData = {
        key: `videos/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.mp4`,
        policy: credentials.policy,
        OSSAccessKeyId: credentials.accessKeyId,
        signature: credentials.signature,
        success_action_status: '200',
        ...options.formData
      };

      // 3. 上传到OSS
      return new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
          url: this.baseURL,
          filePath: filePath,
          name: 'file',
          formData: formData,
          success: (res) => {
            if (res.statusCode === 200) {
              const fileUrl = `${this.baseURL}/${formData.key}`;
              resolve({
                url: fileUrl,
                key: formData.key
              });
            } else {
              reject(new Error(`上传失败，状态码：${res.statusCode}`));
            }
          },
          fail: reject
        });

        // 进度监听
        if (options.onProgress) {
          uploadTask.onProgressUpdate(options.onProgress);
        }
      });
    } catch (error) {
      console.error('OSS上传失败:', error);
      throw error;
    }
  }
}

export default new OSSUpload();